/**
 * 竞争对手详情
 */
(function($) {
  var pageData = {};
  var pageCount = 1;
  var filterType = 3;
  var pageNumber = 0;
  var opponentList = new Array();
  var DATA_OPERATORS = ["", "联通", "电信"],
      DATA_PROD_TYPE = ["", "IDC", "专线", "集团电话", "物联网"],
      DATA_PROD_TYPE_GROUP = [
        [],
        ["IDC_INFO","INT_BANDWIDTH","MACHINE_ROOM","RACK_NUM","RACK_POWER","COST","START_DATE","END_DATE","AMOUNT"],
        ["LINE_INFO","BUSI_TYPE","BANDWIDTH","ARTI_NUM","COST","START_DATE","END_DATE","AMOUNT","AVE_TRAFFIC"],
        ["TEL_INFO","ACCESS","INSTALLED_NUM","INSTALLED_ADDR","SEG_NO","COST","START_DATE","END_DATE","AMOUNT"],
        ["IOT_INFO","NET_TYPE","BUSI_TYPE","APP_SCENE","PACK_COST","COST","START_DATE","END_DATE","AMOUNT"]
      ],
      DATA_PROD_TYPE_GROUP_CN = [
        [],
        ["IDC","互联网出口带宽","机房位置","机架数量","机架功耗","资费","合同起始时间","合同终止时间","总收入（年）"],
        ["专线","业务类型","带宽","专线条数","资费","合同起始时间","合同终止时间","总收入（年）","语音专线的日均话务量"],
        ["集团电话","接入方式","装机量","装机地址","话务号段","资费","合同起始时间","合同终止时间","总收入（年）"],
        ["物联网","网络类型","业务类型","应用场景","资费套餐","资费","合同起始时间","合同终止时间","总收入（年）"]
      ],
      DATA_LINE_BUSI_TYPE = ["","本地数据专线","省内跨地市专线","跨省专线","互联网专线","单一号码集团电话业务","多号码集团电话业务","呼叫中心（自用型、经营型)"];
  
  var idcData;
  /*
  封装参数
  */
  var getMyParams = function(id,operator,prod_type) {
    var params = "?";
    var myParam = getParams();
    if (myParam) {
      params += myParam;
      if (id) {
        params += "&";
      }
    }
    if (id) {
      params = params.replace(/\&id\=(\d+)\&/, "&");
      params += "id=" + id;
    }
    if (operator&&prod_type) {
      params += "&operator="+operator+"&prod_type="+prod_type;
    }
    
    console.log("params=" + params);
    return params;
  };

  var bind = function(object, clickFunc) {
    itemOnClick(object, clickFunc);
  }

  var itemOnClick = function(object, clickFunc) {
    $(object).off("click"); //取消li事件
    /*li事件*/
    $(object).on("click", function() {
      var $siblingsNode = $(this).siblings();
      var primaryClass = "select-item";
      var defaultColor = "#fff";
      var selectColor = "#0c79b1";

      if ($siblingsNode.hasClass(primaryClass)) {
        $siblingsNode.removeClass(primaryClass);
        $siblingsNode.css("background-color", defaultColor);
      }
      if ($(this).hasClass(primaryClass)) {
        $(this).removeClass(primaryClass);
        $(this).css("background-color", defaultColor);
      } else {
        $(this).addClass(primaryClass);
        $(this).css("background-color", selectColor);
      }
      clickFunc(this);
      event.stopPropagation();
    });
  }

  var  createObject =function (title,value){
　　var obj = new Object();
　　obj.title = title;
　　obj.value = value;
　　return obj;
　}

  /*
  显示数据
  */
  var showOpponentData = function(data) {
    if(data&&data.PROD_DETAIL&&data.PROD_DETAIL[0]) {
      if(data.PROD_DETAIL[0].START_DATE) {
        data.PROD_DETAIL[0].START_DATE = dateFormat(data.PROD_DETAIL[0].START_DATE, "YYYY-MM-DD");
      }
      if(data.PROD_DETAIL[0].END_DATE) {
        data.PROD_DETAIL[0].END_DATE = dateFormat(data.PROD_DETAIL[0].END_DATE, "YYYY-MM-DD");
      }
    }
    var baseData = {
      "prod_type": DATA_PROD_TYPE[data.PROD_TYPE],
      "group_name": createObject("集团客户名称", decodeURIComponent(getParamValue("group_name"))),
      "operator": createObject("运营商", DATA_OPERATORS[data.OPERATOR])
    };

    $("#detail_title").html(baseData.prod_type+"对手信息");
    opponentList.push(baseData.group_name);
    opponentList.push(baseData.operator);
    var cnt = 1;
    $.each(data.PROD_DETAIL[0], function(i, item) {
      //处理专线的业务类型的值和显示值的转换
      if(data.PROD_TYPE === "2" && cnt === 1) data.PROD_DETAIL[0][DATA_PROD_TYPE_GROUP[data.PROD_TYPE][cnt]] = DATA_LINE_BUSI_TYPE[data.PROD_DETAIL[0][DATA_PROD_TYPE_GROUP[data.PROD_TYPE][cnt]]];
      
      var obj = createObject(DATA_PROD_TYPE_GROUP_CN[data.PROD_TYPE][cnt], data.PROD_DETAIL[0][DATA_PROD_TYPE_GROUP[data.PROD_TYPE][cnt]]);
      opponentList.push(obj);
      cnt++;
    });
    cnt = 1;

    
    var $tpl = $('#amz-detail');
    var source = $tpl.text();
    var template = Handlebars.compile(source);
    var myData = {
      list: opponentList,
      "error": "没有集团信息"
    };

    $("#opponent-list").children('li').remove();
    $("#opponent-list").children('div').remove();

    var html = template(myData);
    $tpl.before(html);
  };


  var loadOpponentData = function() {
    id = getParamValue("id");
    var groupNo = getParamValue("group_no"),
        operator = decodeURIComponent(getParamValue("operator")),
        prod_type = decodeURIComponent(getParamValue("prod_type"));
    console.log("id="+id);
    params = {
      "requestData":"<CUST_CODE>"+groupNo+"</CUST_CODE>"+
      "<OPERATOR>"+DATA_OPERATORS.indexOf(operator)+
      "</OPERATOR><PROD_TYPE>"+DATA_PROD_TYPE.indexOf(prod_type)+"</PROD_TYPE>"+
      "<PROD_ID>"+id+"</PROD_ID>"
    };

    $.ajax({
      type: "post",
      contentType: "application/json",
      data: JSON.stringify(params),
      // url: "../../../opponent/getIdcDetailsById?id=" + id,
      /**
      * ↓clearCacheNo: 解决IOS读取缓存的问题
      */
      url: Constants.restHost + "rest/opp/compProdQryDetail?clearCacheNo="+Math.random(),
      dataType: "json",
      async: true,
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
        console.log("data = " + data);
        pageData = data.rtnCode;
        console.info(data.rtnCode);
        if (data.rtnCode != 1000) {
          console.log("获取RPC接口返回失败！code:" + data.rtnMsg);
          return;
        }
        $("#modal-loading").modal('close');
        // 编辑页面传入ID
        //idcData = JSON.stringify(data.data);
        // idcData = data.data.id;
        idcData = data.return.RESULT.PROD_ID;

        showOpponentData(data.return.RESULT);
      },
      error: function(textStatus) {
        $("#modal-loading").modal('close');
        showBottomMsg("获取信息失败！");
        console.info("request error:");
      }
    });
  };

  var deleteSuccess = function(){
    params = getMyParams();
    if(params.indexOf("&id=")!=-1){
      params = params.substring(0, params.indexOf("&id="));
    }
    window.location.href = "opponent_list.html" + params;
  }

  var deleteOpponentData = function() {
    $("#modal-loading").modal('open');
    id = getParamValue("id");
    var groupNo = getParamValue("group_no"),
        operator = decodeURIComponent(getParamValue("operator")),
        prod_type = decodeURIComponent(getParamValue("prod_type"));
    console.log("id="+id);

    var params = {
    "requestData":
      "<OPER_TYPE>DELETE</OPER_TYPE>"+
      "<OPER_TIME>"+dateFormat(new Date(), "YYYY/MM/DD hh:mm:ss")+"</OPER_TIME>"+
      "<CUST_CODE>"+groupNo+"</CUST_CODE>"+
      "<OPERATOR>"+DATA_OPERATORS.indexOf(operator)+"</OPERATOR>"+
      "<PROD_TYPE>"+DATA_PROD_TYPE.indexOf(prod_type)+"</PROD_TYPE>"+
      "<PROD_ID>"+id+"</PROD_ID>"
    };

    $.ajax({
      type: "post",
      contentType: "application/json",
      data: JSON.stringify(params),
      // url: "../../../opponent/deleteOpponent?id=" + id,
      url: Constants.restHost + "rest/opp/compProdChg",
      dataType: "json",
      async: true,
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
        showLoadingBar($("#loadingbar"), false);
        console.log("data = " + data);
        pageData = data.rtnCode;
        console.info(data.rtnCode);
        if (data.rtnCode != 1000) {
          console.log("获取RPC接口返回失败！code:" + data.rtnMsg);
          return;
        }
        if(data.return.HEADER.RESPONSE.CODE != 0000) {
          showErrorMsg(data.return.HEADER.RESPONSE.CODE);
          console.log("删除失败！code:"+data.return.HEADER.RESPONSE.CODE);
          return;
        }
        console.log("消息:"+data.return.RESULT.RETURN_MSG);

        $("#modal_content").html("删除成功！");
        setTimeout(deleteSuccess,2000);
      },
      error: function(textStatus) {
        $("#modal-loading").modal('close');
        console.info("request error:");
        alert("删除失败，请联系管理员！");
      }
    });
  };

  $(function() {
    /*滚动条*/
    var $doc = $(document);
    $doc.scroll(function() {
      console.log("height = " + ($doc.height() - $(window).height()));
      console.log("scrollTop = " + Math.ceil($doc.scrollTop()));
      console.log("Math.ceil($doc.scrollTop()) = " + Math.ceil($doc.scrollTop()));
      if (Math.ceil($doc.scrollTop()) >= ($doc.height() - $(window).height())) {
        var $msg = $("#no-data-msg");
        console.log("debug 1");
        if (!$.isEmptyObject(pageData)) {
          console.log("debug 2");
          if (!$msg.hasClass("am-hide")) {
            console.log("debug 3");
            $msg.addClass("am-hide");
          }
          console.log("pageNumber=" + pageNumber);
          pageNumber++;
          loadGroupData(pageNumber);
        } else {
          console.log("debug 5");
          if ($msg.hasClass("am-hide")) {
            console.log("debug 6");
            $msg.removeClass("am-hide");
          }
        }
      }
    });


    $("#search_btn").on("click", function() {
      operator = $("#searchType").val();
      pageNumber=0;
      opponentList=[];
      loadOpponentData(pageNumber, operator);
    });
    $("#search").on("click", function() {
      $('#search-modal').modal('open');
    });
    $("#delete_btn").on('click', function(){
      $('#delete-confirm-modal').modal('open');
    });
    $("#edit_btn").on('click', function(){
    	window.location.href = "idc_edit.html?" + getMyParams(idcData);;
    });
    $("#delete_confirm_btn").on("click", function() {      
      deleteOpponentData();
    });
    $("#modal-loading").modal('open');
    loadOpponentData(pageNumber, "");
  });
})(jQuery);